package com.amani.module.medical_supplies.biz;


import com.amani.module.medical_supplies.entity.PurchaseOrder;
import com.amani.module.medical_supplies.entity.PurchaseOrderDetail;
import com.amani.module.medical_supplies.feign.IGroupService;
import com.amani.module.medical_supplies.mapper.PurchaseOrderMapper;
import com.amani.module.medical_supplies.vo.PurchaseDetailVO;
import com.amani.module.medical_supplies.vo.PurchaseVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.api.vo.group.GroupInfo;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.auth.client.jwt.UserAuthUtil;
import com.github.wxiaoqi.security.auth.common.util.jwt.IJWTInfo;
import com.github.wxiaoqi.security.common.biz.BaseBiz;

import com.github.wxiaoqi.security.common.context.BaseContextHandler;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.amani.module.medical_supplies.util.OrderNumUtil;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.util.Query;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.ParameterizedType;
import java.math.BigDecimal;
import java.util.*;

/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * @create 2017-06-08 16:23
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PurchaseBiz extends BaseBiz<PurchaseOrderMapper, PurchaseOrder> {
    private final BigDecimal zero = new BigDecimal(0);

    @Autowired
    PurchaseDetailBiz detailBiz;
    @Autowired
    WorkflowBiz workflowBiz;
    @Autowired
    IGroupService iGroupService;
    @Autowired
    private UserAuthUtil userAuthUtil;
    @Autowired
    UserAuthConfig userAuthConfig;

    @Override
    public void insertSelective(PurchaseOrder entity) {
        super.insertSelective(entity);
    }

    @Override
    //@CacheClear(pre="user{1.username}")
    public void updateSelectiveById(PurchaseOrder entity) {
        super.updateSelectiveById(entity);
    }


    public void addPurchase(PurchaseVO vo, ObjectRestResponse response) {
        if (vo.getItems() == null || vo.getItems().isEmpty()) {
            response.setMessage("没有明细");
            return;
        }
        try {
            PurchaseOrder purchaseOrder = null;
            purchaseOrder = new PurchaseOrder();
            setPurchaseOrder(purchaseOrder, vo);
            List<PurchaseOrderDetail> detailList = new ArrayList<>();
            int rId = 1;
            BigDecimal totalMoney = zero;
            BigDecimal totalNum = zero;
            for (PurchaseDetailVO dvo : vo.getItems()
                    ) {
                PurchaseOrderDetail detail = new PurchaseOrderDetail();
                setPurchaseDetail(detail, dvo, rId);
                totalMoney.add(dvo.get金额());
                totalNum.add(dvo.get申购数量());
                detailList.add(detail);
                rId++;
            }
            purchaseOrder.set金额合计(totalMoney);
            purchaseOrder.set单据编号(OrderNumUtil.CreateOrderNum(OrderNumUtil.OrderType.PurchaseOrder));
            super.insertSelective(purchaseOrder);
            for (PurchaseOrderDetail detail2 : detailList
                    ) {
                detail2.setPid(purchaseOrder.getId());
                detailBiz.insertSelective(detail2);
            }
        } catch (Exception e) {
            throw new BaseException("提交新增失败：" + e.getMessage());
        }
    }

    private void setPurchaseDetail(PurchaseOrderDetail detail, PurchaseDetailVO dvo, int rId) {
        /*detail.setPid(dvo.getPid());
        detail.setRid(rId);
        detail.set价a(dvo.get价a());
        detail.set价b(dvo.get价b());
        detail.set价c(dvo.get价c());
        detail.set价d(dvo.get价e());
        detail.set价e(dvo.get价e());
        detail.set价f(dvo.get价f());
        detail.set供应商(dvo.get供应商());
        detail.set包装(dvo.get包装());
        detail.set单价(dvo.get单价());
        detail.set单位(dvo.get单位());
        detail.set厂商(dvo.get厂商());
        detail.set发票号码(dvo.get发票号码());
        detail.set发货要求(dvo.get发货要求());
        detail.set合同价(dvo.get合同价());
        detail.set商品(dvo.get商品());
        detail.set开票日期(dvo.get开票日期());
        detail.set开票金额(dvo.get开票金额());
        detail.set执行价(dvo.get执行价());
        detail.set申购数量(dvo.get申购数量());
        detail.set科室请购单号(dvo.get科室请购单号());
        detail.set税率(dvo.get税率());
        detail.set考核价n(dvo.get考核价n());
        detail.set考核价y(dvo.get考核价y());
        detail.set订货要求(dvo.get订货要求());
        detail.set说明(dvo.get说明());
        detail.set请购科室(dvo.get请购科室());*/
        BeanUtils.copyProperties(dvo, detail);
        detail.setRid(rId);
        BigDecimal money = zero;
        if (detail.get单价() != null && detail.get单价().compareTo(zero) > 0) {
            money = detail.get申购数量().multiply(detail.get单价());
        }
        detail.set金额(money);

    }

    private void setPurchaseOrder(PurchaseOrder purchaseOrder, PurchaseVO vo) {
        BeanUtils.copyProperties(vo, purchaseOrder);
        /*purchaseOrder.set付款方式(vo.get付款方式());
        purchaseOrder.set供应商(vo.get供应商());
        purchaseOrder.set到货日期(vo.get到货日期());
        purchaseOrder.set制单人(vo.get制单人());
        purchaseOrder.set单据日期(vo.get单据日期());
        purchaseOrder.set单据编号(vo.get单据编号());
        purchaseOrder.set发票类型(vo.get发票类型());
        purchaseOrder.set备案审批意见(vo.get备案审批意见());
        purchaseOrder.set备案审批明细(vo.get备案审批明细());
        purchaseOrder.set备案审批状态(vo.get备案审批状态());
        purchaseOrder.set备案流程id(vo.get备案流程id());
        purchaseOrder.set备案流程结束标志(vo.get备案流程结束标志());
        purchaseOrder.set备注(vo.get备注());
        purchaseOrder.set审批备注(vo.get审批备注());
        purchaseOrder.set审批意见(vo.get审批意见());
        purchaseOrder.set审批状态(vo.get审批状态());
        purchaseOrder.set当前审批人(vo.get当前审批人());
        purchaseOrder.set当前审批级别(vo.get当前审批级别());
        purchaseOrder.set支付方式(vo.get支付方式());
        purchaseOrder.set收货科室(vo.get收货科室());
        purchaseOrder.set数量(vo.get数量());
        purchaseOrder.set是否备案(vo.get是否备案());
        purchaseOrder.set是否实施(vo.get是否实施());
        purchaseOrder.set是否收货(vo.get是否收货());
        purchaseOrder.set流程id(vo.get流程id());
        purchaseOrder.set流程结束标志(vo.get流程结束标志());
        purchaseOrder.set状态(vo.get状态());
        purchaseOrder.set申购员(vo.get申购员());
        purchaseOrder.set申购科室(vo.get申购科室());
        purchaseOrder.set税率(vo.get税率());
        purchaseOrder.set请购机构(vo.get请购机构());
        purchaseOrder.set采购管理类型(vo.get采购管理类型());
        purchaseOrder.set采购类型(vo.get采购类型());
        purchaseOrder.set金额(vo.get金额());
        purchaseOrder.set金额合计(vo.get金额合计());*/
    }

    public Object selPurchaseById(int id) {
        if (id > 0) {
            try {
                PurchaseOrder purchaseOrder = super.selectById(id);
                PurchaseVO purchaseVO = new PurchaseVO();
                setPurchaseVO(purchaseVO, purchaseOrder);
                List<PurchaseOrderDetail> detailList = detailBiz.selectByPid(id);
                List<PurchaseDetailVO> dvoList = new ArrayList<>();
                if (detailList != null && !detailList.isEmpty()) {
                    for (PurchaseOrderDetail detail : detailList
                            ) {
                        PurchaseDetailVO dvo = new PurchaseDetailVO();
                        setPurchaseDetailVO(dvo, detail);
                        dvoList.add(dvo);
                    }
                }
                purchaseVO.setItems(dvoList);
                return purchaseVO;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private void setPurchaseDetailVO(PurchaseDetailVO dvo, PurchaseOrderDetail detail) {
        BeanUtils.copyProperties(detail, dvo);
    }

    private void setPurchaseVO(PurchaseVO purchaseVO, PurchaseOrder purchaseOrder) {
        BeanUtils.copyProperties(purchaseOrder, purchaseVO);
    }

    public void updatePurchaseById(PurchaseVO vo, ObjectRestResponse response) {
        if (vo.getItems() == null || vo.getItems().isEmpty()) {
            response.setMessage("没有明细");
            return;
        }
        try {
            PurchaseOrder purchaseOrder = null;
            purchaseOrder = new PurchaseOrder();
            setPurchaseOrder(purchaseOrder, vo);
            List<PurchaseOrderDetail> detailList = new ArrayList<>();
            int rId = 1;
            BigDecimal totalMoney = zero;
            BigDecimal totalNum = zero;
            for (PurchaseDetailVO dvo : vo.getItems()
                    ) {
                PurchaseOrderDetail detail = new PurchaseOrderDetail();
                setPurchaseDetail(detail, dvo, rId);
                totalMoney.add(dvo.get金额());
                totalNum.add(dvo.get申购数量());
                detailList.add(detail);
                rId++;
            }
            purchaseOrder.set金额合计(totalMoney);
            super.updateSelectiveById(purchaseOrder);
            detailBiz.deleteByPid(purchaseOrder.getId());
            for (PurchaseOrderDetail detail : detailList
                    ) {
                detail.setPid(purchaseOrder.getId());
                detailBiz.insertSelective(detail);
            }
        } catch (Exception e) {
            throw new BaseException("提交更新失败：" + e.getMessage());
        }
    }

    public void commitApprovelById(int id, String bpmn, ObjectRestResponse response) {
        try {
            if (bpmn == null || "".equals(bpmn.trim())) {
                throw new BaseException("获取医耗审批流程失败");
            }
            if (id > 0) {
                PurchaseOrder purchaseOrder = super.selectById(id);
                if (purchaseOrder != null) {
                    HashMap<String, Object> variables = new HashMap<>();
                    variables.put("company", 5);
                    variables.put("dept", 82);
                    variables.put("user", 1161);
                    variables.put("amount", 500);
                    variables.put("level1", "设备科" + "医耗采购一级审批");
                    variables.put("level2", "医耗采购二级审批");
                    variables.put("level3", "医耗采购三级审批");
                    String processDefiniteKey = bpmn.trim();
                    String bussinessKey = processDefiniteKey + ":" + id;
                    ProcessInstance pi = workflowBiz.startProcess(processDefiniteKey, bussinessKey, variables);
                    if (pi != null) {
                        purchaseOrder.set流程id(pi.getId());
                        //提交审批
                        purchaseOrder.set审批状态(purchaseOrder.PURCHASE_CONFIRM);
                        super.updateSelectiveById(purchaseOrder);
                    } else {
                        throw new BaseException("保存审批实例失败！");
                    }
                    response.setMessage("提交审批成功");
                    response.setStatus(1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public TableResultResponse selectpageApprovalByQuery(Query query, String processDefiniteKey) {
        //查找当前用户的角色
        String userId = null;
        Page<Object> result = new Page<>();
        List<PurchaseOrder> list = new ArrayList<>();
        try {
            userId = BaseContextHandler.getUserID();
            if (userId != null) {
                //List<GroupInfo> listGroups = iGroupService.getGroupsByUserId(Integer.parseInt(userId));
                List<GroupInfo> listGroups = iGroupService.getGroupsByUserId();
                String deptName = "设备科";
                List<String> groupNames = new LinkedList<>();
                for (GroupInfo g:listGroups
                     ) {
                    String groupName = g.getName();
                    if(groupName.contains("医耗采购一级审批")){
                        groupName = deptName+groupName;
                    }
                    groupNames.add(groupName);
                }
                //根据角色查找对应的审批任务
                List<Task> Task = workflowBiz.queryTodoListbyRole(processDefiniteKey,groupNames);
                //需要分页在此处理
                //根据代办任务查找业务单据
                List<Integer> purchaseIds = new ArrayList<>();
                for (Task task:Task
                     ) {
                    String bussinessKey = workflowBiz.getBussinessKeyByProcessInstanceId(task.getProcessInstanceId());
                    String purchaseId = bussinessKey.split(":")[1];
                    purchaseIds.add(Integer.valueOf(purchaseId));
                }
                Class<PurchaseOrder> clazz = (Class<PurchaseOrder>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
                Example example = new Example(clazz);
                Example.Criteria criteria = example.createCriteria();
                if (query.entrySet().size() > 0) {
                    for (Map.Entry<String, Object> entry : query.entrySet()) {
                        criteria.andLike(entry.getKey(), "%" + entry.getValue().toString() + "%");
                    }
                }
                criteria.andIn("id",purchaseIds);
                result = PageHelper.startPage(query.getPage(), query.getLimit());
                list = mapper.selectByExample(example);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new TableResultResponse(result.getTotal(), list);
    }
}
